package com.ssm.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Import(Board.class)
public class ConvertTest {

    @Bean
    public CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
        Map<Class<?>, Class<? extends PropertyEditor>> propertyMap = new HashMap<>();
        propertyMap.put(Fruit.class, StringToFruitPropertyEdit.class);

        customEditorConfigurer.setCustomEditors(propertyMap);
        return customEditorConfigurer;
    }

    public static void main(String[] args) {
//        StringToFruitPropertyEdit propertyEdit = new StringToFruitPropertyEdit();
//        propertyEdit.setAsText("Apple");
//
//        Fruit fruit = (Fruit) propertyEdit.getValue();
//        System.out.println(fruit);

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConvertTest.class);
        Board board = applicationContext.getBean(Board.class);
        board.test();

        Board board1 = applicationContext.getBean("board", Board.class);
        System.out.println(board1);
    }
}


/**
 * 餐桌
 */
@Service
class Board {

    @Value("fruit")
    private Fruit fruit;

    public void test() {
        System.out.println("test fruit ： " + fruit);
    }
}

/**
 * 类型转换器
 */
class StringToFruitPropertyEdit extends PropertyEditorSupport implements
        PropertyEditor {


    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Fruit fruit = new Fruit();
        fruit.setName(text);
        this.setValue(fruit);
    }

}

/**
 * 水果类
 */
class Fruit {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}